package vn.ugame.filter;

import java.io.IOException;
import java.util.List;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import vn.ugame.model.bl.Configuration;
import vn.ugame.model.bl.ModuleManager;
import vn.ugame.model.entity.Module;

public class RequestFilter implements Filter {

    private FilterConfig filterConfig;

    public RequestFilter() {
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");


        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        Configuration configuration = Configuration.getInstance();
        if (!configuration.isLoaded()) {
            try {
                configuration.load();
            } catch (Exception ex) {
                ex.printStackTrace();
                httpResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }            
        }

        String requestURI = httpRequest.getRequestURI();
        requestURI = requestURI.replaceAll(httpRequest.getContextPath(), "");

        if ("/".equals(requestURI)) {
            requestURI = "/store";
        }

        if (requestURI.startsWith("/ugame")) {
            chain.doFilter(request, response);
            return;
        }

        ModuleManager manager = new ModuleManager();
        List<Module> modules = null;
        try {
            modules = manager.findAllModules();
        } catch (Exception ex) {
            ex.printStackTrace(httpResponse.getWriter());
            //httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        for (Module module : modules) {
            if (requestURI.toLowerCase().startsWith("/" + module.getName().toLowerCase())) {
                RequestDispatcher dispatcher = httpRequest.getRequestDispatcher("/ugame" + requestURI);
                dispatcher.forward(request, response);
                return;
            }
        }

        chain.doFilter(request, response);
    }

    public void destroy() {
    }
}
